import dynamic from 'next/dynamic'
import omit from 'lodash-es/omit'
import { useRouter } from 'next/router'
import { devicePlatform } from '@/utils/utils'
import { useEffect, useMemo, useState } from 'react'
import { hotSearchData } from '@/store'
import { useSetRecoilState, useRecoilState } from 'recoil'
import { getTopData } from '@/api/home'
import chunk from 'lodash-es/chunk'
import { pcStore } from '@/store'
import EventBus from '@/utils/emitter'
import Header from '@c/header'
import HeaderPhone from '@c/header-phone'
import { useSetUserInfo } from '@/utils/hooks'
import { injectScript } from '@/utils/utils'

const Backup = dynamic(() => import('@c/backup'))
const ModalDownload = dynamic(() => import('@c/modal/modal-download'))
const LoginBox = dynamic(() => import('@c/login-box'))
const ModalLogout = dynamic(() => import('@c/modal/modal-logout'))
const ModalPay = dynamic(() => import('@c/modal/modal-pay'))
const ModalPayH5 = dynamic(() => import('@c/modal/modal-pay-h5'))
const ModalRobot = dynamic(() => import('@c/modal/modal-robot'))

const Index = ({ Component, pageProps }) => {
  const router = useRouter()
  const [user, setUserInfo] = useSetUserInfo()
  const setHotSearchData = useSetRecoilState(hotSearchData)
  const { pathname } = router
  const [openVip, setOpenVip] = useState(false)
  const [openOut, setOpenOut] = useState(false)
  const [openIn, setOpenIn] = useState(false)
  const [currKey, setCurrKey] = useState(1)
  const [pc, setPc] = useRecoilState(pcStore)
  const [isAndroid, setAndroid] = useState(false)
  const [showRobot, toggleShowRobot] = useState(false)
  // 热搜索数据获取
  const getHotData = async () => {
    try {
      const res = await getTopData()
      const initData = res.data.data.map((item, index) => ({
        ...item,
        index: index + 1
      }))
      setHotSearchData(chunk(initData, 6))
    } catch (error) {}
  }

  // 存储邀请人id
  const cacheInviteId = () => {
    const { invite_code } = router.query
    if (invite_code) {
      localStorage.setItem('invite_code', invite_code)
    }
  }
  useEffect(() => {
    const { isPC, isIOS } = devicePlatform()
    setPc(isPC)
    setAndroid(!isIOS && !isPC)
    const token = localStorage.getItem('token')
    setUserInfo(token)
    getHotData()
  }, [])

  const isDownShow = useMemo(() => {
    return isAndroid && !['/download', '/vip', '/search-phone', '/invite','/market','/privacy','/temp-login',''].includes(router.pathname)
  }, [isAndroid, router.pathname])

  // 用户属性设置。
  useEffect(() => {
    cacheInviteId()
    setTimeout(() => {
      try {
        gtag('set', 'user_properties', {
          user_logged_in: user?.isLogin ? 'true' : 'false',
          user_is_vip: user?.isVip ? 'true' : 'false',
          enter_page: router.asPath
        })
      } catch (error) {}
    }, 200)
  }, [router.asPath, user])

  const withoutHeaderArr = ['/privacy', '/search-phone', '/temp-login','/market']

  useEffect(() => {
    EventBus.on('openVipDialog', key => {
      setCurrKey(key)
      setOpenVip(true)
    })
    EventBus.on('openLoginOut', () => {
      setOpenOut(true)
    })
    EventBus.on('openIn', () => {
      setOpenIn(true)
    })
    EventBus.on('toggleRobot', type => {
      toggleShowRobot(type)
    })
    return () => {
      EventBus.offAll('openVipDialog')
      EventBus.offAll('openLoginOut')
      EventBus.offAll('openIn')
      EventBus.offAll('toggleRobot')
    }
  }, [])

  //用于懒加载一些首屏不用的代码
  useEffect(() => {
    setTimeout(async () => {
      await injectScript('https://www.googletagmanager.com/gtag/js?id=G-J3Y4NBW6EF', 'gtag')
      await injectScript('/js/google.js', 'google')
    }, 1000)
  }, [])

  return (
    <>
      <main className="layoutMain">
        {withoutHeaderArr.includes(pathname) ? null : (
          <>
            <Header className="hideWhenPhone" url={pageProps.layoutProps.url} />
            <HeaderPhone className="hideWhenPc" />
            <Backup />
          </>
        )}

        <Component {...omit(pageProps, ['layoutProps'])} />
      </main>
      <div id="message-root"></div>
      {isDownShow ? <ModalDownload /> : null}
      {/* 登入 */}
      {openIn && <LoginBox onClose={() => setOpenIn(false)} />}
      {/* 登出 */}
      {openOut && <ModalLogout onClose={() => setOpenOut(false)} />}
      {/* 套餐弹窗 */}
      {openVip ? (
        pc ? (
          <ModalPay vipData={pageProps.vipData} currKey={currKey} onClose={() => setOpenVip(false)} />
        ) : (
          <ModalPayH5 vipData={pageProps.vipData} currKey={currKey} onClose={() => setOpenVip(false)} />
        )
      ) : null}
      {showRobot && <ModalRobot />}
    </>
  )
}

export default Index
